package m202311.d20;

/**
 * @author haocongshun
 * @date 2023/11/20 19:42:30
 */

/**
 * 28. 找出字符串中第一个匹配项的下标
 */
public class Q28 {
    public int strStr(String haystack, String needle) {
        if (haystack.length() == needle.length()) {
            return haystack.equals(needle) ? 0 : -1;
        }
        for (int i = 0; i < haystack.length() - needle.length() +1; i++) {
            if (isStrStr(haystack, needle, i)) {
                return i;
            }
        }
        return -1;
    }

    public boolean isStrStr(String haystack, String needle, int index) {
        for (int i = 0; i < needle.length(); i++) {
            if (haystack.charAt(i + index) != needle.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}
